import React, { useState, useEffect, useContext } from 'react';
import { Button } from 'antd';
import { ChatContentContext } from '@/pages/chat';

enum AnalysisType {
  YOY = 'yoy',    // 同比分析
  MOM = 'mom',    // 环比分析
  ATTR = 'attr'   // 归因分析
}

interface ShowMoreAnalysisProps {
  type?: AnalysisType;
  data?:any;
}

const ShowMoreAnalysis: React.FC<ShowMoreAnalysisProps> = ({ 
  type = AnalysisType.ATTR,  // 默认为归因分析
  data
}) => {
  const { showAnalysis, setShowAnalysis } = useContext(ChatContentContext);

  // 记录是否需要发送消息
  const [pendingMsg, setPendingMsg] = useState(false);

  const sendMsgToIframe = () => {
    const analysisFrame = document.querySelector('iframe[title="更多分析"]');
    if (analysisFrame && analysisFrame.contentWindow) {
      const iframeParams = {
          analysisType: type,
          metricColumnName: data.metricColumnName,
          metricModelId: data.metricModelId,
          predictStartTime: data.predictStartTime,
          predictEndTime: data.predictEndTime
      }
      //预测分析 增加 步长 参数
      if(!type && data.metricModelId){
        iframeParams.predictStep = data.predictStep ?? 6;
      }
      analysisFrame.contentWindow.postMessage({
        type: 'ANALYSIS_QUERY',
        payload: iframeParams
      }, window.location.origin);
    }
  };

  // 监听 showAnalysis 变为 true 时再发送消息
  useEffect(() => {
    if (showAnalysis && pendingMsg) {
      sendMsgToIframe();
      setPendingMsg(false);
    }
  }, [showAnalysis, pendingMsg]);

  const handleClick = () => {
    if (!showAnalysis) {
      setShowAnalysis(true);
      setPendingMsg(true);
    } else {
      sendMsgToIframe();
    }
  };


  return (
    <>
      { window.location.pathname !== '/moreAnalysis_setting' && <Button
        type="link"
        className={`flex items-center mt-2`}
        onClick={handleClick}
      >
        更多分析 >>
      </Button>
      }
    </>
  );
};

export default ShowMoreAnalysis;